'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { useForm } from 'react-hook-form'
import { useAuthStore } from '@/lib/store'
import api from '@/lib/api'
import { toast } from 'react-hot-toast'
import { Button } from '@/components/ui/button'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'

interface BookingFormProps {
  spotId: number
  price: number
  inventory: number
}

interface BookingForm {
  quantity: number
  visitDate: string
  contactName: string
  contactPhone: string
}

export default function BookingForm({ spotId, price, inventory }: BookingFormProps) {
  const router = useRouter()
  const { isAuthenticated } = useAuthStore()
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [showConfirm, setShowConfirm] = useState(false)
  const [bookingData, setBookingData] = useState<BookingForm | null>(null)
  
  const form = useForm<BookingForm>({
    defaultValues: {
      quantity: 1,
      visitDate: new Date().toISOString().split('T')[0],
      contactName: '',
      contactPhone: ''
    }
  })

  const onSubmit = async (data: BookingForm) => {
    if (!isAuthenticated) {
      router.push('/login')
      return
    }

    // 显示确认对话框
    setBookingData(data)
    setShowConfirm(true)
  }

  const handleConfirm = async () => {
    if (!bookingData) return

    try {
      setIsSubmitting(true)
      const response = await api.post('/api/orders', {
        spot_id: spotId,
        quantity: bookingData.quantity,
        total_price: bookingData.quantity * price,
        visit_date: bookingData.visitDate,
        contact_name: bookingData.contactName,
        contact_phone: bookingData.contactPhone
      })

      toast.success(response.data.message || '预订成功')
      setShowConfirm(false)
      
      // 使用返回的订单ID进行跳转
      if (response.data.order_id) {
        router.push(`/orders/${response.data.order_id}`)
      } else {
        router.push('/orders') // 如果没有订单ID，跳转到订单列表页
      }
    } catch (error: any) {
      toast.error(error.response?.data?.detail || '预订失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
          <FormField
            control={form.control}
            name="quantity"
            rules={{
              required: '请输入数量',
              min: { value: 1, message: '至少预订1张票' },
              max: { value: inventory, message: `最多可预订${inventory}张票` }
            }}
            render={({ field: { onChange, ...field } }) => (
              <FormItem>
                <FormLabel>数量</FormLabel>
                <FormControl>
                  <Input
                    type="number"
                    {...field}
                    onChange={(e) => onChange(parseInt(e.target.value))}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="visitDate"
            rules={{ required: '请选择游玩日期' }}
            render={({ field }) => (
              <FormItem>
                <FormLabel>游玩日期</FormLabel>
                <FormControl>
                  <Input type="date" {...field} min={new Date().toISOString().split('T')[0]} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="contactName"
            rules={{ required: '请输入联系人姓名' }}
            render={({ field }) => (
              <FormItem>
                <FormLabel>联系人</FormLabel>
                <FormControl>
                  <Input {...field} placeholder="请输入联系人姓名" />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="contactPhone"
            rules={{ 
              required: '请输入联系电话',
              pattern: {
                value: /^1[3-9]\d{9}$/,
                message: '请输入正确的手机号'
              }
            }}
            render={({ field }) => (
              <FormItem>
                <FormLabel>联系电话</FormLabel>
                <FormControl>
                  <Input {...field} placeholder="请输入联系电话" />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <div className="flex items-center justify-between text-base">
            <span className="font-medium text-gray-900">总价</span>
            <span className="font-medium text-gray-900">
              ¥{price * (form.watch('quantity') || 0)}
            </span>
          </div>

          <Button
            type="submit"
            className="w-full"
            disabled={isSubmitting}
          >
            {isSubmitting ? '提交中...' : '立即预订'}
          </Button>
        </form>
      </Form>

      <Dialog open={showConfirm} onOpenChange={setShowConfirm}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认预订信息</DialogTitle>
          </DialogHeader>
          {bookingData && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="font-medium">数量：</span>
                  {bookingData.quantity} 张
                </div>
                <div>
                  <span className="font-medium">总价：</span>
                  ¥{price * bookingData.quantity}
                </div>
                <div>
                  <span className="font-medium">游玩日期：</span>
                  {bookingData.visitDate}
                </div>
                <div>
                  <span className="font-medium">联系人：</span>
                  {bookingData.contactName}
                </div>
                <div>
                  <span className="font-medium">联系电话：</span>
                  {bookingData.contactPhone}
                </div>
              </div>
              <div className="flex justify-end space-x-4">
                <Button variant="outline" onClick={() => setShowConfirm(false)}>
                  返回修改
                </Button>
                <Button onClick={handleConfirm} disabled={isSubmitting}>
                  {isSubmitting ? '提交中...' : '确认预订'}
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </>
  )
} 